﻿using System.Collections.ObjectModel;
using EduAssess.Models;

namespace EduAssess.Services;

public class TestState
{
    private Test? _currentTest;

    public Test? CurrentTest
    {
        get => _currentTest;
        set
        {
            _currentTest = value;
            ClearState();
        }
    }

    private int _questionNumber;

    public int QuestionNum
    {
        get => _questionNumber;
        set => _questionNumber = value > CurrentTest.QuestionCount ? CurrentTest.QuestionCount : value;
    }

    public ObservableCollection<Question> RightAnswers { get; private set; }
    public ObservableCollection<Question> WrongAnswers { get; private set; }
    public bool ShowRightAnswers { get; set; }
    public int TestResult => (int)((double)RightAnswers.Count / CurrentTest.QuestionCount * 100);

    public bool CanCheckAnswer { get; set; }

    private void ClearState()
    {
        RightAnswers = [];
        WrongAnswers = [];
    }

    public void ChangeTestParameters(int start, int end, int qNum, bool mixQ, bool mixA)
    {
        SelectQuestionInterval(start, end);

        if (mixQ) CurrentTest.Questions.Shuffle();
        if (mixA) MixAnswers();

        SelectQuestions(qNum);
    }

    private void SelectQuestionInterval(int start, int end)
    {
        CurrentTest.Questions =
            new ObservableCollection<Question>(CurrentTest.Questions.Skip(start - 1).Take(end - start + 1));
    }

    private void SelectQuestions(int num)
    {
        CurrentTest.Questions = new ObservableCollection<Question>(CurrentTest.Questions.Take(num));
    }

    private void MixAnswers()
    {
        foreach (var question in CurrentTest.Questions)
        {
            question.Answers.Shuffle();
        }
    }
}